#include "client.h"

void putsCommand(client_task_t * task){
    // 处理 puts 命令
    int fd = open(task->train.buff, O_RDWR);
    /* //断点重传 */
    off_t lenhalf;
    recvn(task->peerfd, &lenhalf, sizeof(lenhalf));
    /* if (lenhalf != 0) { */
    /*     //4将文件偏移到文件 */
    /*     printf("断点重传\n"); */
    /*     printf("lenhalf\n"); */
    /*     if(lseek(fd, lenhalf, SEEK_SET) == -1){ */
    /*         error(1,errno,"lseek "); */

    /*     } */
    /* } */

    if (lenhalf != 0) {
        printf("断点续传\n");
    }
    printf("offset = %ld\n", lenhalf);

    //发送文件的总长度
    struct stat st;
    memset(&st, 0, sizeof(st));
    fstat(fd, &st);
    printf("filelength: %ld\n", st.st_size);//off_t
    printf("sizeof(st.st_size): %ld\n", sizeof(st.st_size));
    sendn(task->peerfd, &st.st_size, sizeof(st.st_size));

    //续传的计算
    off_t length = st.st_size - lenhalf;
    
    if (length >= 100 * 1024 * 1024) {
        int ret = sendfile(task->peerfd, fd, &lenhalf, length);
        printf("ret: %d, send file over.\n", ret);
        
    } else {//小文件采用循环发送 
            //4将文件偏移到文件
        if(lseek(fd, lenhalf, SEEK_SET) == -1){
            error(1,errno,"lseek ");
        }
        
        while (1) {
            memset(&task->train, 0, sizeof(task->train));
            int ret = read(fd, task->train.buff, sizeof(task->train.buff));
            if (ret == 0) {
                //文件读取完了,退出循环并通知对方退出
                task->train.len = 0;
                sendn(task->peerfd, &task->train.len, 4);
                break;
            }
            task->train.len = ret;
            task->train.type =(CmdType)(-1);
            ret = sendn(task->peerfd, &task->train, 4 + 4 + task->train.len);
            if (ret == -1) {
                break;//发生错误
            }
        }//while
     } 
}
